import DownloadTemplate from '@/pages/BatchTask/components/DownloadTemplate';
import { queryCompanies } from '@/pages/SystemUser/service';
import { Role } from '@/utils/types.d';
import { ImportOutlined } from '@ant-design/icons';
import { ModalForm, ProFormSelect, ProFormUploadButton } from '@ant-design/pro-components';
import { Button, message } from 'antd';
import type { RcFile } from 'antd/lib/upload';
import { useModel } from 'umi';
import { importArrearOrder } from '../service';

const ImportOrder = (props: { func: () => void }) => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const userRole = currUser?.role;
  return (
    <ModalForm
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 16 }}
      width="35vw"
      title="导入欠费订单"
      trigger={
        <Button type="primary">
          <ImportOutlined /> 导入欠费订单
        </Button>
      }
      onFinish={async (values) => {
        const { data_file, ownerId } = values;
        if (!data_file || !data_file[0]) {
          message.warn({ content: '请选择文件! ', key: 'import_arrear' });
        }
        const file = data_file[0];
        const isLt200K = file.size / 1024 < 200;
        if (!isLt200K) {
          message.error({
            content: '文件过大，请上传一个小于200k的文件',
            key: 'import_arrear',
          });
          return;
        }
        const formData = new FormData();
        formData.append('data_file', file.originFileObj);
        formData.append('ownerId', ownerId);
        const res = await importArrearOrder(formData);
        if (res.success) {
          props.func();
          message.success({
            content: res.message,
            key: 'import_arrear',
          });
          return true;
        }
        message.error({
          content: res.message,
          key: 'import_arrear',
        });
        return false;
      }}
    >
      {userRole === Role.ADMIN && (
        <ProFormSelect
          name="ownerId"
          label="选择用户"
          width="md"
          rules={[{ required: true, message: '请选择用户' }]}
          debounceTime={300}
          showSearch
          placeholder="请选择用户"
          request={(val) => queryCompanies(val.keyWords)}
        />
      )}
      <ProFormUploadButton
        label="上传文件"
        title="xlsx格式，大小小于200K"
        name="data_file"
        accept=".xlsx"
        fieldProps={{
          maxCount: 1,
          customRequest: () => {},
          beforeUpload: (file: RcFile): Promise<boolean> =>
            new Promise((resolve, rejects) => {
              const { name } = file;

              // .xlsx*表示匹配所有带有 .xlsx 的字段，$表示匹配字符串结尾位置
              const nameRegExp = new RegExp('.xlsx*$');
              const isXlsx = nameRegExp.test(name);
              const isLt200K = file.size / 1024 < 200;
              if (!isXlsx) {
                message.error({
                  content: '文件类型错误, 请上传一个xlsx表格文件',
                  key: 'import_arrear',
                });
                rejects();
                return;
              }
              if (!isLt200K) {
                message.error({
                  content: '文件过大，请上传一个小于200k的文件',
                  key: 'import_arrear',
                });
                rejects(false);
                return;
              }
              resolve(false);
            }),
        }}
      />
      <div
        style={{
          margin: '0 auto',
          width: '75%',
          padding: '15px 8px ',
          background: '#f4f6fa',
        }}
      >
        <div style={{ fontWeight: 'bold' }}>
          请确保订单中的路段和泊位均已录入系统，否则导入不会成功
        </div>
        <div>导入订单数量如超过100笔，请前往批量任务进行操作</div>
        <div>如果您没有导入模板文件，请点击下载：</div>
        <DownloadTemplate type="import_order_m100" />
        <div style={{ margin: '10px 0 5px' }}>
          使用excel编辑模板时，请确认输入的内容为文本格式。符号请在英文状态下输入。
        </div>
      </div>
    </ModalForm>
  );
};

export default ImportOrder;
